package com.restkeeper.response.interceptor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Value("${app.type:''}")
    private String appType;

    @Bean
    public HandlerInterceptor MyInterceptor() {
        if ("microApp".equals(appType)){
            return new MicroHandlerInterceptor();
        }else {
            return new WebHandlerInterceptor();
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptor = registry.addInterceptor(MyInterceptor());
        // 拦截所有、排除
        interceptor.addPathPatterns("/**")
                .excludePathPatterns("/login","/login");
    }

    /**
     * 跨域支持配置
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true).allowedOrigins("*").allowedMethods("GET", "PUT", "DELETE", "POST", "OPTIONS").maxAge(3600);
    }

//    @Bean
//    public CorsWebFilter corsWebFilter() {
//        org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//        CorsConfiguration config = new CorsConfiguration();
//        config.setAllowCredentials(true); // 允许凭证请求
//        config.addAllowedOrigin("*"); // 允许任何域进行跨域请求
//        config.addAllowedHeader("*"); // 允许任何头进行跨域请求
//        config.addAllowedMethod("*"); // 允许任何方法进行跨域请求
//        source.registerCorsConfiguration("/**", config);
//        return new CorsWebFilter(source);
//    }

}

